// 1.导入相关依赖包
const express = require('express')
const { ApolloServer, gql } = require('apollo-server-express')

// 2.定义数据类型
/**
 * query类型是默认客户端查询的类型
 * 该类型在服务端必须存在且唯一
 */

const typeDefs = gql`
  #课程类型
  type Course {
    cname: String
    score: Float
  }
  #学生类型
  type Student {
    id: Int
    sname: String
    age: Int
    scores(cname: String): [Course]
  }
  #查询类型
  type Query {
    hello: String
    stu: Student
  }
`

// 3.解析数据类型对应的具体数据
const resolvers = {
  Student: {
    scores: (parent, args) => {
      console.log(args.cname)
      if (args.cname === '数学' || args.cname === '英语') {
        return parent.scores.filter(item => {
          return item.cname === args.cname
        })
      } else {
        return parent.scores
      }
    }
  },
  Query: {
    hello: () => 'Hello World!',
    stu: (parent, args) => {
      return {
        id: 1,
        sname: '张三',
        scores: [
          {
            cname: '数学',
            score: 88
          },
          {
            cname: '语文',
            score: 65
          },
          {
            cname: '英语',
            score: 45
          }
        ]
      }
    }
  }
}

// 4.整合apollo-server和express
/**
 *   typeDefs,resolvers 属性名是固定的
 */
const server = new ApolloServer({
  typeDefs,
  resolvers
})

const app = express()
server.applyMiddleware({ app })

// 5.监听启动
app.listen({ port: 4000 }, () => console.log('Now browse to http://localhost:4000' + server.graphqlPath))

/**
query param{
  hello
stu{
  id
  sname
  age
  math:scores(cname:"数学"){
    cname
    score
  }
  english:scores(cname:"英语"){
    cname
    score
  }
}
}
 */
